package com.yanboo.common.aspect;

import com.yanboo.common.constant.DataFilterConstant;
import com.yanboo.common.utils.SecurityUtils;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Aspect
@Slf4j
public class DataFilterAdvice {

    @PersistenceContext
    private EntityManager entityManager;

    @Around("@annotation(com.yanboo.common.annotation.EnableFilter)")
    public Object doProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Filter dataPermissionFilter = entityManager.unwrap(Session.class).enableFilter(DataFilterConstant.FILTER);
            List<Long> currentUserDataScope = SecurityUtils.getCurrentUserDataScope();
            if (currentUserDataScope.isEmpty()) {
                entityManager.unwrap(Session.class).disableFilter(DataFilterConstant.FILTER);
                return joinPoint.proceed();
            }
            dataPermissionFilter.setParameterList(DataFilterConstant.PARAM, currentUserDataScope);
            return joinPoint.proceed();
        } catch (Throwable ex) {
            log.error(ex.getMessage());
            throw ex;
        } finally {
            entityManager.unwrap(Session.class).disableFilter(DataFilterConstant.FILTER);
        }
    }
}
